<template>
  <div class="container mx-auto px-4 py-6">
    <div class="flex justify-between items-center mb-6">
      <div class="flex items-center">
        <button @click="$router.back()" class="mr-4 p-2 text-gray-500 hover:text-gray-700 focus:outline-none">
          <ArrowLeftIcon class="h-6 w-6" />
        </button>
        <h2 class="text-2xl font-semibold text-gray-800">{{ isEdit ? '编辑维修记录' : '添加维修记录' }}</h2>
      </div>
    </div>

    <div class="bg-white rounded-xl shadow-lg p-6">
      <form @submit.prevent="handleSubmit" class="space-y-6">
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- 设备选择 -->
          <div>
            <label for="equipmentId" class="block text-sm font-medium text-gray-700">设备 <span class="text-red-500">*</span></label>
            <select id="equipmentId" v-model="form.equipmentId" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
              <option value="">请选择设备</option>
              <option v-for="equipment in equipmentList" :key="equipment.id" :value="equipment.id">
                {{ equipment.name }} ({{ equipment.code }})
              </option>
            </select>
          </div>

          <!-- 维修日期 -->
          <div>
            <label for="repairDate" class="block text-sm font-medium text-gray-700">维修日期 <span class="text-red-500">*</span></label>
            <input type="date" id="repairDate" v-model="form.repairDate" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" />
          </div>

          <!-- 问题描述 -->
          <div class="md:col-span-2">
            <label for="problemDescription" class="block text-sm font-medium text-gray-700">问题描述 <span class="text-red-500">*</span></label>
            <textarea id="problemDescription" v-model="form.problemDescription" rows="3" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="请详细描述设备出现的问题"></textarea>
          </div>

          <!-- 维修厂家 -->
          <div>
            <label for="repairCompany" class="block text-sm font-medium text-gray-700">维修厂家 <span class="text-red-500">*</span></label>
            <input type="text" id="repairCompany" v-model="form.repairCompany" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="请输入维修厂家名称" />
          </div>

          <!-- 维修费用 -->
          <div>
            <label for="repairCost" class="block text-sm font-medium text-gray-700">维修费用 <span class="text-red-500">*</span></label>
            <input type="number" id="repairCost" v-model="form.repairCost" step="0.01" min="0" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="请输入维修费用" />
          </div>

          <!-- 责任人 -->
          <div>
            <label for="responsiblePerson" class="block text-sm font-medium text-gray-700">责任人 <span class="text-red-500">*</span></label>
            <input type="text" id="responsiblePerson" v-model="form.responsiblePerson" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="请输入责任人姓名" />
          </div>

          <!-- 处理人 -->
          <div>
            <label for="handlerId" class="block text-sm font-medium text-gray-700">处理人 <span class="text-red-500">*</span></label>
            <select id="handlerId" v-model="form.handlerId" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
              <option value="">请选择处理人</option>
              <option v-for="user in userList" :key="user.id" :value="user.id">
                {{ user.realName }} ({{ user.username }})
              </option>
            </select>
          </div>

          <!-- 维修结果 -->
          <div>
            <label for="repairResult" class="block text-sm font-medium text-gray-700">维修结果 <span class="text-red-500">*</span></label>
            <textarea id="repairResult" v-model="form.repairResult" rows="3" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="请描述维修结果"></textarea>
          </div>

          <!-- 状态 -->
          <div>
            <label for="status" class="block text-sm font-medium text-gray-700">状态 <span class="text-red-500">*</span></label>
            <select id="status" v-model="form.status" required class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm">
              <option value="">请选择状态</option>
              <option value="REPAIRING">维修中</option>
              <option value="COMPLETED">已完成</option>
            </select>
          </div>

          <!-- 备注 -->
          <div class="md:col-span-2">
            <label for="remark" class="block text-sm font-medium text-gray-700">备注</label>
            <textarea id="remark" v-model="form.remark" rows="2" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm py-2 px-3 focus:outline-none focus:ring-indigo-500 focus:border-indigo-500 sm:text-sm" placeholder="请输入备注信息"></textarea>
          </div>
        </div>

        <!-- 提交按钮 -->
        <div class="flex justify-end space-x-3 pt-6 border-t border-gray-200">
          <button type="button" @click="$router.back()" class="px-4 py-2 border border-gray-300 rounded-md shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">
            取消
          </button>
          <button type="submit" :disabled="loading" class="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 disabled:opacity-50">
            {{ loading ? '保存中...' : (isEdit ? '更新' : '保存') }}
          </button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ArrowLeftIcon } from '@heroicons/vue/24/outline'
import request from '@/utils/request'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const equipmentList = ref([])
const userList = ref([])

const form = reactive({
  equipmentId: '',
  repairDate: '',
  problemDescription: '',
  repairCompany: '',
  repairCost: '',
  responsiblePerson: '',
  repairResult: '',
  status: '',
  remark: '',
  handlerId: null
})

const isEdit = computed(() => !!route.params.id)

// 加载设备列表
const loadEquipmentList = async () => {
  try {
    const response = await request.get('/equipment/list?pageSize=1000')
    equipmentList.value = response.data.records || []
  } catch (error) {
    console.error('加载设备列表失败:', error)
    showMessage('加载设备列表失败', 'error')
  }
}

// 加载用户列表
const loadUserList = async () => {
  try {
    const response = await request.get('/users?pageSize=1000')
    userList.value = response.data.records || []
  } catch (error) {
    console.error('加载用户列表失败:', error)
    showMessage('加载用户列表失败', 'error')
  }
}

// 加载维修记录详情
const loadRepairRecord = async () => {
  if (!isEdit.value) return
  
  try {
    loading.value = true
    const response = await request.get(`/equipment-repair/${route.params.id}`)
    const record = response.data
    
    Object.assign(form, {
      equipmentId: record.equipmentId,
      repairDate: record.repairDate ? record.repairDate.split('T')[0] : '',
      problemDescription: record.problemDescription,
      repairCompany: record.repairCompany,
      repairCost: record.repairCost,
      responsiblePerson: record.responsiblePerson,
      repairResult: record.repairResult,
      status: record.status,
      remark: record.remark,
      handlerId: record.handlerId
    })
  } catch (error) {
    console.error('加载维修记录失败:', error)
    showMessage('加载维修记录失败', 'error')
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    loading.value = true
    
    const requestData = {
      equipmentId: parseInt(form.equipmentId),
      repairDate: form.repairDate,
      description: form.problemDescription,
      repairCompany: form.repairCompany,
      repairCost: parseFloat(form.repairCost),
      responsiblePerson: form.responsiblePerson,
      repairResult: form.repairResult,
      status: form.status,
      remark: form.remark,
      handlerId: parseInt(form.handlerId)
    }
    
    if (isEdit.value) {
      await request.put(`/equipment-repair/${route.params.id}`, requestData)
      showMessage('维修记录更新成功', 'success')
    } else {
      await request.post('/equipment-repair', requestData)
      showMessage('维修记录创建成功', 'success')
    }
    
    router.push('/equipment-repair')
    
  } catch (error) {
    console.error('保存维修记录失败:', error)
    showMessage('保存维修记录失败', 'error')
  } finally {
    loading.value = false
  }
}

// 消息提示
const showMessage = (message, type = 'info') => {
  const messageEl = document.createElement('div')
  messageEl.className = `fixed top-4 right-4 px-6 py-3 rounded-lg text-white z-50 ${
    type === 'success' ? 'bg-green-500' :
    type === 'warning' ? 'bg-yellow-500' :
    type === 'error' ? 'bg-red-500' :
    'bg-blue-500'
  }`
  messageEl.textContent = message
  document.body.appendChild(messageEl)

  setTimeout(() => {
    if (document.body.contains(messageEl)) {
      document.body.removeChild(messageEl)
    }
  }, 3000)
}

onMounted(() => {
  loadEquipmentList()
  loadUserList()
  loadRepairRecord()
})
</script>
